let oWarp = document.querySelector(".warp"),
    oLevel = document.querySelector(".level"),
    oMap = document.querySelector(".map"),
    oScore = document.querySelector(".score"),
    oAllbiu = document.querySelector(".allbiu"),
    oSettlement = document.querySelector(".settlement"),
    restart = document.querySelector(".restart")

init()
    //初始化
function init() {
    // oWarp.style.backgroundImage = "url(./img/bg_2.jpg)"
    //选择难度
    let allP = oLevel.querySelectorAll("p")
    for (let i = 0; i < allP.length; i++) {
        allP[i].onclick = function(e) {
            startGame(i, {
                x: e.clientX - oWarp.offsetLeft,
                y: e.clientY - oWarp.offsetTop
            })
        }
    }
}
// 开始游戏
function startGame(level, position) {

    clearMap()
    MapBackground(level)
    let myPlane = caeatePlane(level, position)
    enemy(level, myPlane)
    oWarp.score = 0
        // console.log(myPlane);

    //restart按钮
    restart.onclick = function() {
        cancelAnimationFrame(oWarp.bgtimer) //背景停止
        oSettlement.style.display = "none"
        oLevel.style.display = "block"
            //清除所有样式
        oScore.innerHTML = 0;
        oMap.innerHTML = `<div class="allbiu"></div>`;
        oAllbiu = document.querySelector(".allbiu")
    }
}
//清除样式
function clearMap() {
    oLevel.style.display = "none"
    oScore.style.display = "block"
}
// 根据等级更换地图 
function MapBackground(level) {
    // oMap.style.backgroundImage = `url(./img/bg_${level + 1}.jpg)`
    oMap.style.backgroundImage = "url(./img/bg_" + (level + 1) + ".jpg)"
    oMap.bgPositionY = 0;
    let speed = [1, 2, 3, 4];
    // 移动背景图片
    (function mapBgMove() {
        oMap.bgPositionY += speed[level];
        // oMap.bgPositionY++;
        oMap.style.backgroundPositionY = oMap.bgPositionY + "px";
        oWarp.bgtimer = requestAnimationFrame(mapBgMove); //不断移动背景的y位置

    }());
}
//创建飞机
function caeatePlane(level, pos) {
    //设置样式
    let oImg = new Image()
    oImg.src = "./img/plane_0.png";
    oImg.width = 70;
    oImg.height = 70;
    oImg.className = "plane"
        // 设置飞机的位置
    let iW = oImg.width / 2,
        iH = oImg.height / 2,
        //飞机移动范围值
        minY = 0,
        maxY = oWarp.offsetHeight - oImg.height,
        minX = -iW,
        maxX = oWarp.offsetWidth - iW
    oImg.style.top = pos.y - iW + "px"
    oImg.style.left = pos.x - iH + "px"

    oMap.appendChild(oImg)
        // 飞机移动
    document.onmousemove = function(e) {
        let left = e.clientX - oWarp.offsetLeft - iW,
            top = e.clientY - oWarp.offsetTop - iH
            //限制飞机移动范围
        left = Math.max(left, minX)
        left = Math.min(left, maxX)
        top = Math.max(top, minY)
        top = Math.min(top, maxY)

        oImg.style.left = left + "px"
        oImg.style.top = top + "px"

    }
    fire(level, oImg)
    return oImg
}
//创建我军子弹
function fire(level, oImg) {

    oWarp.biuTimer = setInterval(() => {
        if (oWarp.score >= 300) {
            createBiu(true, -1);
            createBiu(true, 1);
        } else {
            createBiu()
        }
    }, [300, 200, 100, 50][level]);

    function createBiu(bool, n) {
        let biuImg = new Image;
        biuImg.src = "./img/fire.png"
        biuImg.width = 30
        biuImg.height = 30
        biuImg.className = "biu"

        let left = oImg.offsetLeft + oImg.width / 2 - biuImg.width / 2
        let top = oImg.offsetTop - biuImg.height + 10

        if (bool) {
            left += (biuImg.width - 10) * n
        }

        biuImg.style.top = top + "px"
        biuImg.style.left = left + "px"

        oAllbiu.appendChild(biuImg)

        //让子弹动起来
        function fireMove() {
            //判断子弹是否存在
            if (biuImg.parentNode) {
                top -= 10
                if (top < -biuImg.height) {
                    oAllbiu.removeChild(biuImg)
                } else {
                    biuImg.style.top = top + "px"
                    requestAnimationFrame(fireMove)
                }
            }
        }
        setTimeout(() => {
            // fireMove()
            requestAnimationFrame(fireMove)
        }, 20);
    }
}
let enemyNum = 1
    //创建敌军
function enemy(level, myPlane) {
    let speed = [5, 6, 7, 8][level], //飞机下落速度
        mapW = oMap.clientWidth,
        mapH = oMap.clientHeight

    // 生成敌军飞机
    oWarp.enemyTimer = setInterval(() => {

        let oEnemy = new Image()
        oEnemy.index = enemyNum % 30 ? 1 : 0;
        oEnemy.src = `./img/enemy_${["big", "small"][oEnemy.index]}.png`
        oEnemy.width = [100, 50][oEnemy.index];
        oEnemy.height = [76, 37][oEnemy.index];
        oEnemy.className = "enemy"
        oEnemy.HP = [10, 1][oEnemy.index]
        oEnemy.speed = speed + (Math.random() * 0.6 - 0.3) * speed;
        oEnemy.speed *= oEnemy.index ? 1 : 0.5;

        let top = -oEnemy.height,
            left = Math.random() * mapW - oEnemy.width / 2
        oEnemy.style.top = top + "px"
        oEnemy.style.left = left + "px"
        oMap.appendChild(oEnemy)

        enemyNum++
        //让敌军动起来
        function enemyMove() {
            if (oEnemy.parentNode) {
                top += oEnemy.speed
                if (top >= mapH) {
                    oWarp.score--; //漏掉飞机减分
                    oScore.innerHTML = oWarp.score;
                    oMap.removeChild(oEnemy)
                } else {
                    oEnemy.style.top = top + "px"
                    let arrBiu = oAllbiu.children
                    for (let i = arrBiu.length - 1; i >= 0; i--) {
                        if (!isCollision(arrBiu[i], oEnemy)) {
                            oAllbiu.removeChild(arrBiu[i])
                            oEnemy.HP--
                                if (oEnemy.HP === 0) {
                                    oWarp.score += [10, 1][oEnemy.index]
                                    oScore.innerHTML = oWarp.score

                                    boom({
                                        x: oEnemy.offsetLeft,
                                        y: oEnemy.offsetTop,
                                        h: oEnemy.width,
                                        w: oEnemy.height,
                                        i: oEnemy.index
                                    })

                                    oMap.removeChild(oEnemy)
                                    return
                                }

                        }
                    }
                    if (myPlane.parentNode && !isCollision(myPlane, oEnemy)) {

                        boom({
                            x: oEnemy.offsetLeft,
                            y: oEnemy.offsetTop,
                            h: oEnemy.width,
                            w: oEnemy.height,
                            i: oEnemy.index
                        })

                        boom({
                            x: myPlane.offsetLeft,
                            y: myPlane.offsetTop,
                            h: myPlane.width,
                            w: myPlane.height,
                            i: 2
                        })

                        oMap.removeChild(myPlane)
                        oMap.removeChild(oEnemy)

                        gameOver()

                        return
                    }
                    requestAnimationFrame(enemyMove)


                }
            }
        }
        requestAnimationFrame(enemyMove)
    }, [360, 280, 200, 100][level]);

}
// 判断是否碰撞
function isCollision(obj1, obj2) {
    //得到对象坐标obj1
    let top1 = obj1.offsetTop,
        bottom1 = top1 + obj1.clientHeight,
        left1 = obj1.offsetLeft,
        right1 = left1 + obj1.clientWidth,
        //obj2
        top2 = obj2.offsetTop,
        bottom2 = top2 + obj2.clientHeight,
        left2 = obj2.offsetLeft,
        right2 = left2 + obj2.clientWidth

    return top1 > bottom2 || bottom1 < top2 || left1 > right2 || right1 < left2

}
//爆炸效果
function boom(data) {
    //生成爆炸图片
    let boomImg = new Image()
    boomImg.src = `./img/${["boom_big", "boom_small", "plane_0"][data.i]}.png`
    boomImg.width = data.w
    boomImg.height = data.h
    boomImg.className = ["boom", "boom", "boom2"][data.i]
    boomImg.style.left = data.x + "px"
    boomImg.style.top = data.y + "px"

    oMap.appendChild(boomImg)


    setTimeout(() => {
        boomImg.parentNode && oMap.removeChild(boomImg)
    }, [1200, 1200, 2500][data.i])
}

//结束游戏
function gameOver() {

    clearInterval(oWarp.enemyTimer) //清除创建敌军
    clearInterval(oWarp.biuTimer) //清楚子弹
    document.onmousemove = null //清除移动事件
    gameSettlement()
}
//游戏结算
function gameSettlement() {
    let final = document.querySelector(".final span"),
        evaluate = document.querySelector(".evaluate span"),
        n = oWarp.score,
        desc;
    if (n < -50) {
        desc = "闪避+MAX！！！";
    } else if (n < 10) {
        desc = "菜得…算了我不想说了…";
    } else if (n < 30) {
        desc = "抠脚侠！";
    } else if (n < 100) {
        desc = "初级飞机大师";
    } else if (n < 200) {
        desc = "中级飞机大师";
    } else if (n < 500) {
        desc = "高级飞机大师";
    } else if (n < 800) {
        desc = "终极飞机大师";
    } else {
        desc = "孤独求败！";
    }

    final.innerHTML = oWarp.score
    evaluate.innerHTML = desc
    oScore.style.display = "none"
    oSettlement.style.display = "block"

}